package cn.lg.soar.mvc.converter;

import cn.lg.soar.common.data.dict.IDict;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

/**
 * 枚举转换器
 * @author luguoxiang
 * @date 2022/9/5
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class IDictConvertFactory implements ConverterFactory<String, Enum> {

    private final static Map<Class<? extends Enum>, Converter<String, ?>> CACHE = new ConcurrentReferenceHashMap<>(128);

    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return (Converter<String, T>) CACHE.computeIfAbsent(targetType, k -> {
            if (IDict.class.isAssignableFrom(k)) {
                return new IDictConverter<>((Class<? extends IDict>) k);
            }
            return new EnumConverter<>(k);
        });
    }

}
